import { ref, computed } from 'vue';
import api from "@/utils/api";
import type {CtrlPlan, ReactionPlan} from "./type.ts";
import {message} from "ant-design-vue";

// 定义响应式变量
export const fetching = ref(false);
export const reactionPlanList = ref<ReactionPlan[]>([]);
export const reactionPlanSearchList = ref<ReactionPlan[]>([]);
export const newReactionPlanName = ref();

// 获取反应计划列表
export const fetchReactionPlans = async () => {
    try {
        const response = await api.get('reactionPlan');
        reactionPlanList.value = response.data;
        return reactionPlanList.value;
    } catch (error) {
        console.error('获取反应计划列表失败:', error);
        throw error;
    }
};

export const onReactionPlanSearch = async (cnDesc: string) => {
    if(reactionPlanList.value===undefined || reactionPlanList.value.length===0){
        await fetchReactionPlans();
    }
    if(reactionPlanList.value){
        reactionPlanSearchList.value = reactionPlanList.value
            .filter(fq => fq.cnDesc.includes(cnDesc))
            .sort((a, b) => a.id - b.id);
    }
    if(cnDesc.length>0){
        newReactionPlanName.value=cnDesc;
    }
};

export const onReactionPlanChange = (value: any, cpReactionPlans: ReactionPlan[]) => {
    if(value){
        // 清空现有的频率数组
        cpReactionPlans.length = 0;
        // 对 value 进行去重处理
        const uniqueValues= [...new Set(value)];

        // 遍历所有去重后的值
        uniqueValues.forEach(reactionPlanDesc => {
            const ifq = reactionPlanList.value.find(fq => fq.cnDesc === reactionPlanDesc);

            if (ifq) {
                cpReactionPlans.push({
                    id: ifq.id,
                    cnDesc: ifq.cnDesc,
                });
            }else{
                if(typeof reactionPlanDesc === 'string'){
                    cpReactionPlans.push({
                        id: undefined,
                        cnDesc: reactionPlanDesc,
                    });
                }
            }
        });
        newReactionPlanName.value=undefined;
    }

};

export const isReactionPlanNew = computed(() => {
    return (newReactionPlanName && newReactionPlanName.value!==undefined)
})

export const onReactionPlanBlur = (ctrlPlan:CtrlPlan) => {
    ctrlPlan.reactionPlanValues=[];
    if (ctrlPlan.reactionPlans) {
        ctrlPlan.reactionPlans.forEach(fq => {
            ctrlPlan.reactionPlanValues?.push(fq.cnDesc);
        });
    }
    if(isReactionPlanNew.value){
        ctrlPlan.reactionPlans.push({
            id:undefined,
            cnDesc:newReactionPlanName.value,
        });
        ctrlPlan.reactionPlanValues.push(newReactionPlanName.value);
    }
};

export const createNewReactionPlan = async (cnDesc: string) => {
    const ofq=reactionPlanList.value.find(fq => fq.cnDesc===cnDesc);
    if(ofq){
        return;
    }
    try {
        fetching.value = true;

        await api.post('/reactionPlan', {
            cnDesc: cnDesc,
        });
        await fetchReactionPlans();
        message.success(`新反应计划【${cnDesc}】创建成功`);
        return true;
    } catch (error) {
        message.error('创建反应计划失败');
        console.error('创建反应计划失败:', error);
        return false;
    } finally {
        fetching.value = false;
    }
};

// 重置反应计划数据
export const resetReactionPlanData = () => {
    reactionPlanList.value = [];
};

// 导出所有方法
export default {
    reactionPlanList,
    reactionPlanSearchList,
    fetchReactionPlans,
    onReactionPlanSearch,
    onReactionPlanChange,
    onReactionPlanBlur,
    createNewReactionPlan,
    resetReactionPlanData
};